﻿using System;
using System.IO;
using System.Collections.Generic;
using System.Linq;
using System.Text;

using Newtonsoft.Json;
using DependencyInjection;

namespace Serialization
{
    public class JSONSerializer : ISerializer
    {
        public JSONSerializer()
        {
            
        }

        public void Save<T>(string filename, T obj)
        {
            JsonSerializer serializer = new JsonSerializer();
            serializer.NullValueHandling = NullValueHandling.Ignore;

            using (StreamWriter sw = new StreamWriter(filename))
            using (JsonWriter writer = new JsonTextWriter(sw))
            {
                serializer.Serialize(writer, obj);
            }
        }

        public T Load<T>(string filename)
        {
            T result = default(T);

            if (File.Exists(filename))
            {
                JsonSerializer serializer = new JsonSerializer();
                serializer.NullValueHandling = NullValueHandling.Ignore;

                using (StreamReader sr = new StreamReader(filename))
                using (JsonReader reader = new JsonTextReader(sr))
                {
                    result = serializer.Deserialize<T>(reader);
                }
            }

            return result;
        }
    }
}
